package main.java.leetcode.简单;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;

public class leetcode350_两个数组交集2 {

    @Test
    public void test(){
        int[] nums1 = new int[]{4,9,9};
        int[] nums2 = new int[]{9,4,9,8,4};
        int[] intersect = intersect(nums1, nums2);
        for (int i:intersect){
            System.out.println(i);
        }
    }

    /**
     * 最大公约数2
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersect(int[] nums1, int[] nums2) {
        int[] result = new int[Math.max(nums1.length,nums2.length)];

        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i =0;i<nums1.length;i++){
            if(map.containsKey(nums1[i])){
                map.put(nums1[i],map.get(nums1[i])+1);
            }else{
                map.put(nums1[i],1);
            }
        }
        int index =0;
        for(int i = 0;i<nums2.length;i++){
            if(map.containsKey(nums2[i])){
                if (map.get(nums2[i])!=0){
                    map.put(nums2[i],map.get(nums2[i])-1);
                    result[index]=nums2[i];
                    index++;
                }
            }
        }
        return Arrays.copyOfRange(result,0,index);
    }

}
